<?php
/**
 * Created by PhpStorm.
 * User: charles
 * Date: 2017-11-18
 * Time: 13:08
 */

namespace App\Http\Controllers\LA;


use App\Http\Controllers\Controller;
use App\Models\Member;
use App\Models\MemberAccount;
use App\Models\WithdrawLog;
use DB;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Session;

class WithdrawController extends Controller
{
    public function index()
    {
        $withdrawLogs = WithdrawLog::query()
            ->orderBy('id', 'desc')
            ->with('member', 'member_account')
            ->paginate(20);
        return view('la.withdraw.index', compact('withdrawLogs'));
    }

    public function pass($id)
    {
        DB::beginTransaction();
        try {
            $withdrawLog = WithdrawLog::findOrfail($id);
            if (1 != $withdrawLog->status) {
                $errors = new Collection();
                $errors->push('提现申请单错误，状态不正确');
                return redirect()->back()->with(compact('errors'));
            }
            $memberAccount = MemberAccount::getMemberAccountByOpenid($withdrawLog->openid);
            if ($withdrawLog->amount - $memberAccount->lock_balance >= 0.01) {
                $errors = new Collection();
                $errors->push('转账中余额不足，不可以提现');
                return redirect()->back()->with(compact('errors'));
            }
            $withdrawLog->status = 2;
            $withdrawLog->save();
            $memberAccount->lock_balance -= $withdrawLog->amount;
            $memberAccount->save();
            DB::commit();
        } catch (\Exception $exception) {
            DB::rollback();
            $errors = new Collection();
            $errors->push($exception->getMessage());
            return redirect()->back()->with(compact('errors'));
        }
        return redirect()->back();
    }

    public function deny($id)
    {
        DB::beginTransaction();
        try {
            $withdrawLog = WithdrawLog::findOrfail($id);
            $withdrawLog->status = 3;
            $withdrawLog->save();
            $memberAccount = MemberAccount::getMemberAccountByOpenid($withdrawLog->openid);
            $memberAccount->balance += $withdrawLog->amount;
            $memberAccount->lock_balance -= $withdrawLog->amount;
            $memberAccount->save();
            DB::commit();
        } catch (\Exception $exception) {
            DB::rollback();
            Log::info('拒绝提现失败，问题：' . $exception->getMessage());
        }
        return redirect()->back();
    }
}